package com.winai.launcher.BroadcastReceiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import com.ks.projectbasictools.utils.LogUtils;
import com.winai.launcher.bean.db.AlarmClockBean;
import com.winai.launcher.common.GlobalPublisher;
import com.winai.launcher.utils.AlarmManagerUtil;
import com.winai.launcher.view.timeManager.AlarmAlertActivity;

import org.litepal.LitePal;

/**
 * 作者：康少
 * 时间：2019/12/13
 * 说明：监听闹钟响了回调
 */
public class CallAlarm extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction() != null && intent.getAction().equals(AlarmManagerUtil.ALARM_ACTION)) {
            LogUtils.i("响应闹钟——>" + intent.getAction());
            Bundle alarmBundle = intent.getBundleExtra("alarmBundle");
            if (alarmBundle != null) {
                AlarmClockBean bean = (AlarmClockBean) alarmBundle.getSerializable("AlarmClockBean");
                int id = Integer.parseInt(bean != null ? bean.getId() : "0");
                /**
                 * ,flag = 0 表示一次性的闹钟
                 * ,flag = 1 表示每天提醒的闹钟(1天的时间间隔)
                 * ,flag = 2 表示按周每周提醒的闹钟（一周的周期性时间间隔）
                 */
                int flag = bean != null ? bean.getAlarmClockType() : 0;
                if (flag != 0) {
                    //按每天或者按星期 循环设置闹钟
                    AlarmManagerUtil.setAlarm(context, bean);
                } else {
                    //删除闹钟
                    LitePal.deleteAll(AlarmClockBean.class, "alarmId = ?", bean.getId());
                    AlarmManagerUtil.cancelAlarm(context, bean);
                    //通知取消闹钟UI
                    GlobalPublisher.Notify(GlobalPublisher.CLOSE_ALARM_UI, id);
                }
                if (bean != null) {
                    execute(context, String.valueOf(id)
                            , bean.getTime()
                            , bean.getRemark());
                }
            }
        }
    }

    /**
     * 说明：执行响铃
     */
    private void execute(Context context, String alarmId, String alarmTime, String alarmRemark) {
        Intent intent1 = new Intent(context, AlarmAlertActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("alarmId", alarmId);
        bundle.putString("alarmTime", alarmTime);
        bundle.putString("alarmRemark", alarmRemark);
        intent1.putExtras(bundle);
        intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent1);
    }
}
